<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MCP测试客户端</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f8f9fa;
        }
        .card {
            background-color: white;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            padding: 20px;
            margin-bottom: 20px;
        }
        h1 {
            color: #2c3e50;
            text-align: center;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #34495e;
        }
        input, select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .btn {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 10px 15px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
            margin-right: 10px;
        }
        .btn-danger {
            background-color: #e74c3c;
        }
        .btn-info {
            background-color: #2ecc71;
        }
        .status {
            padding: 15px;
            border-radius: 4px;
            margin-top: 20px;
        }
        .status-disconnected {
            background-color: #ffebee;
            color: #c62828;
        }
        .status-connected {
            background-color: #e8f5e9;
            color: #2e7d32;
        }
        .log-container {
            max-height: 200px;
            overflow-y: auto;
            background-color: #f5f5f5;
            padding: 10px;
            border-radius: 4px;
            border: 1px solid #ddd;
            margin-top: 15px;
            font-family: monospace;
        }
        .log-entry {
            margin-bottom: 5px;
            padding: 2px 0;
            border-bottom: 1px solid #eee;
        }
        .heartbeat-indicator {
            display: inline-block;
            width: 12px;
            height: 12px;
            border-radius: 50%;
            background-color: #ddd;
            margin-left: 10px;
        }
        .heartbeat-active {
            background-color: #4caf50;
            box-shadow: 0 0 5px #4caf50;
            animation: pulse 1s infinite;
        }
        @keyframes pulse {
            0% { opacity: 0.7; }
            50% { opacity: 1; }
            100% { opacity: 0.7; }
        }
        .form-select {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }
        .btn-primary {
            background-color: #2196F3;
        }
        .result-container {
            margin-top: 15px;
            padding: 10px;
            background-color: #f8f9fa;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        pre {
            margin: 0;
            white-space: pre-wrap;
            word-wrap: break-word;
            background-color: #f1f1f1;
            padding: 10px;
            border-radius: 4px;
            max-height: 200px;
            overflow-y: auto;
        }
        .service-form {
            background-color: #f9f9f9;
            padding: 15px;
            margin-top: 10px;
            border-radius: 4px;
            border: 1px solid #eee;
        }
        .form-control {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
            font-family: monospace;
        }
    </style>
</head>
<body>
    <div class="card">
        <h1>MCP测试客户端 <span id="heartbeat-indicator" class="heartbeat-indicator"></span></h1>
        
        <div class="form-group">
            <label for="protocol-select">协议模式</label>
            <select id="protocol-select" class="form-select">
                <option value="rest">REST API</option>
                <option value="jsonrpc">JSON-RPC 2.0</option>
            </select>
        </div>
        
        <div class="form-group">
            <label for="server-url">服务器地址</label>
            <input type="text" id="server-url" value="http://localhost:3001">
        </div>
        
        <div class="form-group">
            <label for="client-id">客户端ID</label>
            <input type="text" id="client-id" value="test-client-" readonly>
        </div>
        
        <div class="form-group">
            <label for="client-version">客户端版本</label>
            <input type="text" id="client-version" value="1.0.0">
        </div>
        
        <div>
            <button id="connect-btn" class="btn">连接服务器</button>
            <button id="disconnect-btn" class="btn btn-danger" disabled>断开连接</button>
            <button id="status-btn" class="btn btn-info">检查服务器状态</button>
        </div>
        
        <div id="connection-status" class="status status-disconnected">
            未连接
        </div>
        
        <h3>日志</h3>
        <div id="log-container" class="log-container"></div>
    </div>
    
    <div class="card" id="jsonrpc-card" style="display: none;">
        <h3>JSON-RPC 2.0测试</h3>
        
        <div class="form-group">
            <label for="jsonrpc-method">方法</label>
            <select id="jsonrpc-method" class="form-select">
                <option value="">-- 请选择方法 --</option>
                <option value="connect">连接</option>
                <option value="disconnect">断开连接</option>
                <option value="heartbeat">心跳检测</option>
                <option value="getStatus">获取状态</option>
                <option value="processData">数据处理</option>
                <option value="logMessage">日志服务</option>
                <option value="sendMetrics">监控服务</option>
                <option value="sendNotification">通知服务</option>
            </select>
        </div>
        
        <div class="form-group">
            <label for="jsonrpc-id">请求ID</label>
            <input type="text" id="jsonrpc-id" value="1">
        </div>
        
        <div id="jsonrpc-params-container">
            <!-- 动态生成的参数表单将在这里显示 -->
        </div>
        
        <div class="form-group">
            <label for="jsonrpc-raw">请求数据(JSON)</label>
            <textarea id="jsonrpc-raw" rows="6" class="form-control" readonly></textarea>
        </div>
        
        <button id="jsonrpc-send-btn" class="btn btn-primary">发送请求</button>
        
        <div id="jsonrpc-result" class="result-container" style="display: none;">
            <h4>响应结果</h4>
            <pre id="jsonrpc-result-content"></pre>
        </div>
    </div>

    <div class="card">
        <h3>MCP服务请求</h3>
        <div class="form-group">
            <label for="service-select">选择服务</label>
            <select id="service-select" class="form-select">
                <option value="">-- 请选择服务 --</option>
                <option value="data-process">数据处理服务</option>
                <option value="log">日志服务</option>
                <option value="monitor">监控服务</option>
                <option value="notification">通知服务</option>
            </select>
        </div>
        
        <!-- 数据处理服务表单 -->
        <div id="data-process-form" class="service-form" style="display: none;">
            <div class="form-group">
                <label for="data-input">处理数据</label>
                <input type="text" id="data-input" placeholder="输入需要处理的数据">
            </div>
            <button id="data-process-btn" class="btn btn-primary">处理数据</button>
        </div>
        
        <!-- 日志服务表单 -->
        <div id="log-form" class="service-form" style="display: none;">
            <div class="form-group">
                <label for="log-type">日志类型</label>
                <select id="log-type">
                    <option value="INFO">INFO</option>
                    <option value="WARNING">WARNING</option>
                    <option value="ERROR">ERROR</option>
                    <option value="DEBUG">DEBUG</option>
                </select>
            </div>
            <div class="form-group">
                <label for="log-message">日志消息</label>
                <input type="text" id="log-message" placeholder="输入日志内容">
            </div>
            <button id="log-btn" class="btn btn-primary">发送日志</button>
        </div>
        
        <!-- 监控服务表单 -->
        <div id="monitor-form" class="service-form" style="display: none;">
            <div class="form-group">
                <label for="client-cpu">CPU使用率(%)</label>
                <input type="number" id="client-cpu" min="0" max="100" value="50">
            </div>
            <div class="form-group">
                <label for="client-memory">内存使用率(%)</label>
                <input type="number" id="client-memory" min="0" max="100" value="60">
            </div>
            <button id="monitor-btn" class="btn btn-primary">发送监控数据</button>
        </div>
        
        <!-- 通知服务表单 -->
        <div id="notification-form" class="service-form" style="display: none;">
            <div class="form-group">
                <label for="notification-target">目标客户端ID</label>
                <input type="text" id="notification-target" placeholder="留空发送给所有客户端">
            </div>
            <div class="form-group">
                <label for="notification-message">通知消息</label>
                <input type="text" id="notification-message" placeholder="输入通知内容">
            </div>
            <button id="notification-btn" class="btn btn-primary">发送通知</button>
        </div>
        
        <div id="service-result" class="result-container" style="display: none;">
            <h4>服务响应结果</h4>
            <pre id="result-content"></pre>
        </div>
    </div>

    <div class="card">
        <h3>服务器信息</h3>
        <div id="server-info">
            <p>服务器ID: <span id="server-id">未知</span></p>
            <p>服务器版本: <span id="server-version">未知</span></p>
            <p>连接客户端数: <span id="client-count">未知</span></p>
            <p>运行时间: <span id="uptime">未知</span></p>
        </div>
    </div>

    <script>
        // 生成随机客户端ID
        document.getElementById('client-id').value += Math.floor(Math.random() * 1000);
        
        const clientId = document.getElementById('client-id').value;
        let connected = false;
        let heartbeatInterval = null;
        
        // 添加日志条目
        function addLogEntry(message) {
            const logContainer = document.getElementById('log-container');
            const entry = document.createElement('div');
            entry.className = 'log-entry';
            entry.textContent = `[${new Date().toLocaleTimeString()}] ${message}`;
            logContainer.appendChild(entry);
            logContainer.scrollTop = logContainer.scrollHeight;
        }
        
        // 更新连接状态
        function updateConnectionStatus(isConnected) {
            const statusElement = document.getElementById('connection-status');
            const connectBtn = document.getElementById('connect-btn');
            const disconnectBtn = document.getElementById('disconnect-btn');
            
            connected = isConnected;
            
            if (isConnected) {
                statusElement.className = 'status status-connected';
                statusElement.textContent = '已连接';
                connectBtn.disabled = true;
                disconnectBtn.disabled = false;
            } else {
                statusElement.className = 'status status-disconnected';
                statusElement.textContent = '未连接';
                connectBtn.disabled = false;
                disconnectBtn.disabled = true;
                
                // Reset server info
                document.getElementById('server-id').textContent = '未知';
                document.getElementById('server-version').textContent = '未知';
                document.getElementById('client-count').textContent = '未知';
                document.getElementById('uptime').textContent = '未知';
                
                // Stop heartbeat
                if (heartbeatInterval) {
                    clearInterval(heartbeatInterval);
                    heartbeatInterval = null;
                }
                
                // Reset heartbeat indicator
                document.getElementById('heartbeat-indicator').className = 'heartbeat-indicator';
            }
        }
        
        // 连接到服务器
        async function connect() {
            const serverUrl = document.getElementById('server-url').value;
            const clientId = document.getElementById('client-id').value;
            const clientVersion = document.getElementById('client-version').value;
            
            addLogEntry(`正在连接到 MCP 服务器: ${serverUrl}`);
            
            try {
                const response = await fetch(`${serverUrl}/mcp/connect`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        clientId: clientId,
                        clientVersion: clientVersion
                    })
                });
                
                const data = await response.json();
                
                if (data.status === 'connected') {
                    updateConnectionStatus(true);
                    addLogEntry(`连接成功! 服务器ID: ${data.serverId}`);
                    
                    // Update server information
                    document.getElementById('server-id').textContent = data.serverId || '未知';
                    
                    // Start heartbeat
                    startHeartbeat();
                } else {
                    addLogEntry(`连接失败: ${JSON.stringify(data)}`);
                }
            } catch (error) {
                addLogEntry(`连接错误: ${error.message}`);
            }
        }
        
        // 断开连接
        async function disconnect() {
            const serverUrl = document.getElementById('server-url').value;
            const clientId = document.getElementById('client-id').value;
            
            if (!connected) {
                addLogEntry('客户端未连接');
                return;
            }
            
            try {
                const response = await fetch(`${serverUrl}/mcp/disconnect`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        clientId: clientId
                    })
                });
                
                const data = await response.json();
                updateConnectionStatus(false);
                addLogEntry(`已断开连接: ${data.message}`);
            } catch (error) {
                addLogEntry(`断开连接错误: ${error.message}`);
            }
        }
        
        // 发送心跳
        async function sendHeartbeat() {
            const serverUrl = document.getElementById('server-url').value;
            const clientId = document.getElementById('client-id').value;
            
            if (!connected) {
                return;
            }
            
            try {
                // 显示心跳动画
                const heartbeatIndicator = document.getElementById('heartbeat-indicator');
                heartbeatIndicator.className = 'heartbeat-indicator heartbeat-active';
                
                const response = await fetch(`${serverUrl}/mcp/heartbeat`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        clientId: clientId
                    })
                });
                
                const data = await response.json();
                addLogEntry(`心跳响应: ${data.status} [${data.timestamp}] [${data.message}]`);
                
                // 心跳响应后1秒关闭动画
                setTimeout(() => {
                    heartbeatIndicator.className = 'heartbeat-indicator';
                }, 1000);
            } catch (error) {
                addLogEntry(`心跳错误: ${error.message}`);
                heartbeatIndicator.className = 'heartbeat-indicator';
            }
        }
        
        // 开始发送心跳
        function startHeartbeat() {
            // 立即发送一次
            sendHeartbeat();
            
            // 然后每5秒发送一次
            heartbeatInterval = setInterval(sendHeartbeat, 5000);
        }
        
        // 检查服务器状态
        async function checkServerStatus() {
            const serverUrl = document.getElementById('server-url').value;
            
            try {
                addLogEntry('正在获取服务器状态...');
                
                const response = await fetch(`${serverUrl}/mcp/status`);
                const data = await response.json();
                
                addLogEntry(`服务器状态: ${JSON.stringify(data)}`);
                
                // 更新服务器信息
                document.getElementById('server-id').textContent = data.serverId || '未知';
                document.getElementById('server-version').textContent = data.version || '未知';
                document.getElementById('client-count').textContent = data.connectedClients || '未知';
                document.getElementById('uptime').textContent = data.uptime || '未知';
                
                return data;
            } catch (error) {
                addLogEntry(`获取服务器状态失败: ${error.message}`);
                return null;
            }
        }
        
        // 事件监听
        document.getElementById('connect-btn').addEventListener('click', connect);
        document.getElementById('disconnect-btn').addEventListener('click', disconnect);
        document.getElementById('status-btn').addEventListener('click', checkServerStatus);
        
        // 初始化
        addLogEntry('测试客户端已启动');

        // 服务选择逻辑
        document.getElementById('service-select').addEventListener('change', function() {
            // 隐藏所有服务表单
            document.querySelectorAll('.service-form').forEach(form => {
                form.style.display = 'none';
            });
            
            // 隐藏结果容器
            document.getElementById('service-result').style.display = 'none';
            
            // 显示选择的服务表单
            const selectedService = this.value;
            if (selectedService) {
                document.getElementById(`${selectedService}-form`).style.display = 'block';
            }
        });

        // 数据处理服务
        document.getElementById('data-process-btn').addEventListener('click', async function() {
            if (!connected) {
                addLogEntry('请先连接到服务器');
                return;
            }
            
            const serverUrl = document.getElementById('server-url').value;
            const clientId = document.getElementById('client-id').value;
            const data = document.getElementById('data-input').value;
            
            if (!data) {
                addLogEntry('请输入需要处理的数据');
                return;
            }
            
            try {
                addLogEntry('正在请求数据处理服务...');
                
                const response = await fetch(`${serverUrl}/mcp/service/data-process`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        clientId,
                        data
                    })
                });
                
                const result = await response.json();
                addLogEntry(`数据处理服务响应: ${result.message}`);
                
                // 显示结果
                displayServiceResult(result);
            } catch (error) {
                addLogEntry(`数据处理服务错误: ${error.message}`);
            }
        });

        // 日志服务
        document.getElementById('log-btn').addEventListener('click', async function() {
            if (!connected) {
                addLogEntry('请先连接到服务器');
                return;
            }
            
            const serverUrl = document.getElementById('server-url').value;
            const clientId = document.getElementById('client-id').value;
            const logType = document.getElementById('log-type').value;
            const logMessage = document.getElementById('log-message').value;
            
            if (!logMessage) {
                addLogEntry('请输入日志内容');
                return;
            }
            
            try {
                addLogEntry('正在发送日志...');
                
                const response = await fetch(`${serverUrl}/mcp/service/log`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        clientId,
                        logType,
                        logMessage
                    })
                });
                
                const result = await response.json();
                addLogEntry(`日志服务响应: ${result.message}`);
                
                // 显示结果
                displayServiceResult(result);
            } catch (error) {
                addLogEntry(`日志服务错误: ${error.message}`);
            }
        });

        // 监控服务
        document.getElementById('monitor-btn').addEventListener('click', async function() {
            if (!connected) {
                addLogEntry('请先连接到服务器');
                return;
            }
            
            const serverUrl = document.getElementById('server-url').value;
            const clientId = document.getElementById('client-id').value;
            const clientCpu = document.getElementById('client-cpu').value;
            const clientMemory = document.getElementById('client-memory').value;
            
            try {
                addLogEntry('正在发送监控数据...');
                
                const response = await fetch(`${serverUrl}/mcp/service/monitor`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        clientId,
                        metrics: {
                            cpu: parseFloat(clientCpu),
                            memory: parseFloat(clientMemory),
                            timestamp: new Date().toISOString()
                        }
                    })
                });
                
                const result = await response.json();
                addLogEntry(`监控服务响应: ${result.message}`);
                
                // 显示结果
                displayServiceResult(result);
            } catch (error) {
                addLogEntry(`监控服务错误: ${error.message}`);
            }
        });

        // 通知服务
        document.getElementById('notification-btn').addEventListener('click', async function() {
            if (!connected) {
                addLogEntry('请先连接到服务器');
                return;
            }
            
            const serverUrl = document.getElementById('server-url').value;
            const clientId = document.getElementById('client-id').value;
            const target = document.getElementById('notification-target').value;
            const message = document.getElementById('notification-message').value;
            
            if (!message) {
                addLogEntry('请输入通知内容');
                return;
            }
            
            try {
                addLogEntry('正在发送通知...');
                
                const response = await fetch(`${serverUrl}/mcp/service/notification`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        clientId,
                        target,
                        message
                    })
                });
                
                const result = await response.json();
                addLogEntry(`通知服务响应: ${result.message}`);
                
                // 显示结果
                displayServiceResult(result);
            } catch (error) {
                addLogEntry(`通知服务错误: ${error.message}`);
            }
        });

        // 显示服务结果
        function displayServiceResult(result) {
            const resultContainer = document.getElementById('service-result');
            const resultContent = document.getElementById('result-content');
            
            resultContent.textContent = JSON.stringify(result, null, 2);
            resultContainer.style.display = 'block';
        }

        // 协议模式选择
        document.getElementById('protocol-select').addEventListener('change', function() {
            const protocolMode = this.value;
            const jsonrpcCard = document.getElementById('jsonrpc-card');
            const serviceCard = document.querySelector('.card:nth-child(2)'); // 原有的服务卡片
            
            if (protocolMode === 'jsonrpc') {
                jsonrpcCard.style.display = 'block';
                serviceCard.style.display = 'none';
            } else {
                jsonrpcCard.style.display = 'none';
                serviceCard.style.display = 'block';
            }
        });

        // JSON-RPC方法选择
        document.getElementById('jsonrpc-method').addEventListener('change', function() {
            const method = this.value;
            updateJsonRpcParams(method);
        });

        // 更新JSON-RPC参数表单
        function updateJsonRpcParams(method) {
            const container = document.getElementById('jsonrpc-params-container');
            container.innerHTML = '';
            
            // 通用参数
            if (method && method !== 'getStatus') {
                const clientIdGroup = document.createElement('div');
                clientIdGroup.className = 'form-group';
                clientIdGroup.innerHTML = `
                    <label for="jsonrpc-param-clientId">客户端ID</label>
                    <input type="text" id="jsonrpc-param-clientId" value="${document.getElementById('client-id').value}">
                `;
                container.appendChild(clientIdGroup);
            }
            
            // 特定方法的参数
            if (method === 'connect') {
                const versionGroup = document.createElement('div');
                versionGroup.className = 'form-group';
                versionGroup.innerHTML = `
                    <label for="jsonrpc-param-clientVersion">客户端版本</label>
                    <input type="text" id="jsonrpc-param-clientVersion" value="${document.getElementById('client-version').value}">
                `;
                container.appendChild(versionGroup);
            } else if (method === 'processData') {
                const dataGroup = document.createElement('div');
                dataGroup.className = 'form-group';
                dataGroup.innerHTML = `
                    <label for="jsonrpc-param-data">处理数据</label>
                    <input type="text" id="jsonrpc-param-data" placeholder="输入需要处理的数据">
                `;
                container.appendChild(dataGroup);
            } else if (method === 'logMessage') {
                const typeGroup = document.createElement('div');
                typeGroup.className = 'form-group';
                typeGroup.innerHTML = `
                    <label for="jsonrpc-param-logType">日志类型</label>
                    <select id="jsonrpc-param-logType">
                        <option value="INFO">INFO</option>
                        <option value="WARNING">WARNING</option>
                        <option value="ERROR">ERROR</option>
                        <option value="DEBUG">DEBUG</option>
                    </select>
                `;
                container.appendChild(typeGroup);
                
                const messageGroup = document.createElement('div');
                messageGroup.className = 'form-group';
                messageGroup.innerHTML = `
                    <label for="jsonrpc-param-logMessage">日志消息</label>
                    <input type="text" id="jsonrpc-param-logMessage" placeholder="输入日志内容">
                `;
                container.appendChild(messageGroup);
            } else if (method === 'sendMetrics') {
                const cpuGroup = document.createElement('div');
                cpuGroup.className = 'form-group';
                cpuGroup.innerHTML = `
                    <label for="jsonrpc-param-cpu">CPU使用率(%)</label>
                    <input type="number" id="jsonrpc-param-cpu" min="0" max="100" value="50">
                `;
                container.appendChild(cpuGroup);
                
                const memoryGroup = document.createElement('div');
                memoryGroup.className = 'form-group';
                memoryGroup.innerHTML = `
                    <label for="jsonrpc-param-memory">内存使用率(%)</label>
                    <input type="number" id="jsonrpc-param-memory" min="0" max="100" value="60">
                `;
                container.appendChild(memoryGroup);
            } else if (method === 'sendNotification') {
                const targetGroup = document.createElement('div');
                targetGroup.className = 'form-group';
                targetGroup.innerHTML = `
                    <label for="jsonrpc-param-target">目标客户端ID</label>
                    <input type="text" id="jsonrpc-param-target" placeholder="留空发送给所有客户端">
                `;
                container.appendChild(targetGroup);
                
                const messageGroup = document.createElement('div');
                messageGroup.className = 'form-group';
                messageGroup.innerHTML = `
                    <label for="jsonrpc-param-message">通知消息</label>
                    <input type="text" id="jsonrpc-param-message" placeholder="输入通知内容">
                `;
                container.appendChild(messageGroup);
            }
            
            // 触发更新请求预览
            updateJsonRpcPreview();
        }

        // 参数字段变更事件
        document.addEventListener('input', function(e) {
            if (e.target.id.startsWith('jsonrpc-param-') || e.target.id === 'jsonrpc-id') {
                updateJsonRpcPreview();
            }
        });

        // 更新JSON-RPC请求预览
        function updateJsonRpcPreview() {
            const method = document.getElementById('jsonrpc-method').value;
            if (!method) return;
            
            const id = document.getElementById('jsonrpc-id').value;
            const params = {};
            
            // 收集参数
            const paramInputs = document.querySelectorAll('[id^="jsonrpc-param-"]');
            paramInputs.forEach(input => {
                const paramName = input.id.replace('jsonrpc-param-', '');
                let value = input.value;
                
                // 对数字类型进行转换
                if (input.type === 'number') {
                    value = parseFloat(value);
                }
                
                // 对metrics特殊处理
                if (method === 'sendMetrics' && (paramName === 'cpu' || paramName === 'memory')) {
                    if (!params.metrics) params.metrics = {};
                    params.metrics[paramName] = value;
                } else {
                    params[paramName] = value;
                }
            });
            
            // 生成JSON-RPC请求
            const request = {
                jsonrpc: '2.0',
                method: method,
                params: params,
                id: id
            };
            
            // 更新预览
            document.getElementById('jsonrpc-raw').value = JSON.stringify(request, null, 2);
        }

        // 发送JSON-RPC请求
        document.getElementById('jsonrpc-send-btn').addEventListener('click', async function() {
            const method = document.getElementById('jsonrpc-method').value;
            if (!method) {
                addLogEntry('请选择JSON-RPC方法');
                return;
            }
            
            // 如果尝试连接，更新连接状态
            if (method === 'connect') {
                connected = false; // 先重置连接状态
            }
            
            try {
                const serverUrl = document.getElementById('server-url').value;
                const jsonRpcEndpoint = `${serverUrl}/jsonrpc`;
                const requestText = document.getElementById('jsonrpc-raw').value;
                
                if (!requestText) {
                    addLogEntry('无效的JSON-RPC请求');
                    return;
                }
                
                const request = JSON.parse(requestText);
                
                addLogEntry(`发送JSON-RPC请求: ${method}`);
                
                const response = await fetch(jsonRpcEndpoint, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: requestText
                });
                
                const result = await response.json();
                addLogEntry(`JSON-RPC响应: ${JSON.stringify(result).substring(0, 100)}...`);
                
                // 显示结果
                const resultContent = document.getElementById('jsonrpc-result-content');
                resultContent.textContent = JSON.stringify(result, null, 2);
                document.getElementById('jsonrpc-result').style.display = 'block';
                
                // 如果是连接请求且成功，更新连接状态
                if (method === 'connect' && result.result && result.result.status === 'connected') {
                    updateConnectionStatus(true);
                    // 更新服务器信息
                    document.getElementById('server-id').textContent = result.result.serverId || '未知';
                }
                
                // 如果是断开连接请求且成功，更新连接状态
                if (method === 'disconnect' && result.result && result.result.status === 'disconnected') {
                    updateConnectionStatus(false);
                }
                
                // 如果是状态请求，更新服务器信息
                if (method === 'getStatus' && result.result) {
                    document.getElementById('server-id').textContent = result.result.serverId || '未知';
                    document.getElementById('server-version').textContent = result.result.version || '未知';
                    document.getElementById('client-count').textContent = result.result.connectedClients || '未知';
                    document.getElementById('uptime').textContent = result.result.uptime || '未知';
                }
                
            } catch (error) {
                addLogEntry(`JSON-RPC请求错误: ${error.message}`);
            }
        });

        // 在页面加载后添加JSON-RPC卡片
        window.addEventListener('DOMContentLoaded', function() {
            const serviceCard = document.querySelector('.card:nth-child(2)');
            const jsonrpcCard = document.getElementById('jsonrpc-card');
            
            // 如果jsonrpcCard不存在，则添加到DOM中
            if (!jsonrpcCard) {
                serviceCard.parentNode.insertBefore(
                    document.getElementById('jsonrpc-card'), 
                    serviceCard.nextSibling
                );
            }
            
            // 初始化请求ID
            document.getElementById('jsonrpc-id').value = Math.floor(Math.random() * 10000) + 1;
        });
    </script>
</body>
</html> 